<template>
	<div class="village-collect">
		<component
			:is="formSlot"
			:confirmText="(step === 4 || checked) ? '确认' : '下一步'"
			@onSubmit="onSubmit"
			@onCancel="onCancel"
			cancelText="上一步"
			:showCancel="step !== 1 && !checked"
		>
			<h3 class="h3-before">基本信息</h3>
			<component
				:is="baseInfo"
				:houseData="buildingInfo"
        :locationInfo="locationInfo"
        showLocation
			>
      </component>
			<template v-if="buildingInfo?.fwbh && +loginInfo?.roletype === 3">
				<h3 class="h3-before">房屋状态</h3>
				<div class="status">
					<van-radio-group v-model="checked">
						<van-radio :name="1">不出租</van-radio>
						<van-radio :name="2">已拆除</van-radio>
<!--						<van-radio :name="0">正常出租</van-radio>-->
					</van-radio-group>
				</div>
			</template>

			<component
				v-if="!checked"
				:is="baseForm"
				:formData="formData"
				:initData="initData"
				:step="step"
			/>
		</component>
	</div>
</template>

<script setup>
import formSlot from '@/components/formSlot'
import baseInfo from './components/baseInfo'
import baseForm from './components/baseForm'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { buildingCollection_hc, buildingBase, updateHouse_hc, updateYhjc_hc } from '@/service/village'
import { useRoute, useRouter } from 'vue-router'
import { Dialog } from 'vant'
import { storeToRefs } from 'pinia'
import { useLoginStore } from '@/store'

const loginStore = useLoginStore()
const { loginInfo } = storeToRefs(loginStore)

const route = useRoute()
const router = useRouter()
const buildingInfo = ref({})
const formData = reactive({})
const initData = ref({})
const step = ref(1)
const checked = ref(0)

const submitNumberKey = [
	'jzrks',
	'zzrs',
	'jzfjs',
	'fjsl',
	'jzscxyaqcksl',
	'jzscmj',
	'jzszlwxdlgybjqs',
	'jzsyjyplmhxts',
	'jzxyssltsl',
	'mhqsl',
	'fytsmz',
	'bdfwjzrydddzxcsl',
	'sstdsyyrkrclzx',
	'gryssdcsszblyyqksddp',
	'wdwhjgfjgqsyyrkrgbdj',
	'cs',
	'xggdjsbp',
	'sfazzzryslpbfytsmd',
	'ckfhwggptzlsl',
	'cjzwqtjyyt',
	'fwyfwdddzxccdsssfayqjshsf',
	'sfszsszsbzhaqckbz',
	'czryrs',
	'ywgdlttxwd',
	'sfazfztsss',
	'sfczddzxcjxdczsltfcd',
	'sstdsfdfzw',
]
const submitStringKey = [
	'jsrysstd',
	// 'sstdjsqk',
	'cjzwqtjyytmsg',
	'cdfs',
	'cdfsqtbz',
  'sfmzstdPhoto'
]

const getBuildBase = async () => {
	const result = await buildingBase({
		fwbh: route.query.fwbh
	})
	buildingInfo.value = {
		...result?.data,
		region: `${result?.data?.xzqdmAlias}-${result?.data?.townAlias}-${result?.data?.villageAlias}`
	}
}

const getCollectInfo = async () => {
	try {
		const result = await buildingCollection_hc({
			fwbh: route.query.fwbh
		})
		if (result?.succ) {
			initData.value = result?.data
			checked.value = result?.data?.data?.fwzt || 0
			submitNumberKey.map(item => {
				formData[item] = (result?.data?.data?.[item] || result?.data?.data?.[item] === 0) ? +result?.data?.data?.[item] : ''
			})
			submitStringKey.map(item => {
				formData[item] = result?.data?.data?.[item]
			})
			// if (result?.data?.jsrysstd === '是') formData.sstdjsqk = result?.data?.sstdjsqk?.split('|')
			formData.cjzwqtjyytmsg = result?.data?.data?.cjzwqtjyytmsg?.split('|')
			formData.cdfs = result?.data?.data?.cdfs?.split('|')
      formData.sfmzstdPhoto = []
			// formData.sfmzstdPhoto = result?.data?.data?.sfmzstdPhoto?.split('|')?.map(item => {
      //   return {
      //     url: item,
      //     status: 'done',
      //     isImage: true,
      //   }
      // })
		}
	} catch (e) {

	}
}
const onCancel = () => {
	step.value--
}

const onSubmit = async () => {
	if (step.value !== 4 && !checked.value) {
		step.value++
		return
	}
	const params = {
		id: initData.value?.data?.id,
		fwbh: buildingInfo.value.fwbh,
		hzxm: buildingInfo.value.hzxm,
    currentlocation: locationInfo.value?.address,
    longitude: locationInfo.value?.lng,
    latitude: locationInfo.value?.lat,
	}
	submitNumberKey.map(item => {
		params[item] = +formData[item]
	})
	submitStringKey.map(item => {
		params[item] = formData[item]
	})
	// if (params.jsrysstd === '是') {
	// 	params.sstdjsqk = params.sstdjsqk?.join('|')
	// }
	params["sfmzstdPhoto"] = params.sfmzstdPhoto?.map(item => {
			return item.url
		})?.join('|')
	params.cjzwqtjyytmsg = params.cjzwqtjyytmsg?.join('|')
	params.cdfs = params.cdfs?.join('|')
	confirmSubmit(params)
}

const confirmSubmit = async (params) => {
	if (!checked.value) {
		sessionStorage.setItem('collentedData', JSON.stringify(params))
		nextTick(() => {
			router.push({
				name: 'verification-village-check',
				query: {
					...route.query
				}
			})
		})
	} else {
		try {
			// const result = await updateHouse_hc({
			// 	id: initData.value?.data?.id,
			// 	fwbh: buildingInfo.value.fwbh,
			// 	hzxm: buildingInfo.value.hzxm,
			// 	fwzt: checked.value,
      //   iscj: route.query.iscj ? +route.query.iscj : null,
      //   detaileid: route.query.detailId || null,
			// })
      const result = await updateYhjc_hc({
        zmpcbase: {
          id: initData.value?.data?.id,
          fwbh: buildingInfo.value.fwbh,
          hzxm: buildingInfo.value.hzxm,
          fwzt: checked.value,
          iscj: route.query.iscj ? +route.query.iscj : null,
          detaileid: route.query.detailId || null,
        },
        zmpcyh: null
      })
			if (result?.succ) {
				if (!checked.value) {
					router.push({
						name: 'verification-village-check',
						query: {
							...route.query
						}
					})
				} else {
					Dialog.alert({
						message: '提交成功',
					}).then(() => {
						router.back()
					})
				}
			}
		} catch (e) {
		}
	}
}

const locationInfo = ref({
  address: null,
  lat: null,
  lng: null,
})

const getLocation = async () => {
  AMap.plugin('AMap.Geolocation', function() {
    var geolocation = new AMap.Geolocation({
      enableHighAccuracy: true, // 是否使用高精度定位，默认：true
      timeout: 10000, // 设置定位超时时间，默认：无穷大
      offset: [10, 20],  // 定位按钮的停靠位置的偏移量
      zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      position: 'RB' //  定位按钮的排放位置,  RB表示右下
    })

    geolocation.getCurrentPosition(function (status, result) {
      console.log('获取地址', status, result)
      if (status === 'complete') {
        locationInfo.value = {
          address: result?.formattedAddress || result?.regeocode?.formattedAddress,
          lat: result?.position?.lat,
          lng: result?.position?.lng,
        }
        // 若定位未获取地址信息 但是获取到经纬度 则调用逆地理解析获取地址
        if (!result?.formattedAddress && !result?.regeocode?.formattedAddress) {
          getAddressByLngLat()
        }
      }
    })
  })
}

const getAddressByLngLat = () => {
  var geocoder = new AMap.Geocoder({
    city: '010', //城市设为北京，默认：“全国”
    radius: 1000 //范围，默认：500
  })
  geocoder.getAddress([locationInfo.value.lng, locationInfo.value.lat], function(status, result) {
    console.log('逆地理解析', status, result)
    if (status === 'complete' && result.regeocode) {
      locationInfo.value = {
        ...locationInfo.value,
        address: result.regeocode.formattedAddress,
      }
    }
  });
}


onMounted( () => {
  getLocation()
	getBuildBase()
	getCollectInfo()
})
</script>

<style scoped lang="less">
.village-collect {
	height: 100%;
	:deep(.form-slot) {
		.van-field__label--required:before {
			display: none;
		}
	}
	h3 {
		margin: 24px auto 12px;
	}
	.status {
		padding: 28px 32px 12px;
		margin: 0 32px;
		display: flex;
		flex-direction: column;
		box-shadow: 0 0 16px 0 rgba(0, 0, 0, .14);
		border-radius: 8px;
		background: #fff;
		:deep(.van-radio-group) {
			display: flex;
			justify-content: flex-end;
			gap: 32px;
		}
	}
}
</style>
